import Singleton from "../../core/design-pattern/Singleton";
import GameSetting from "../../data/GameSetting";
import GlobalValue from "../../data/GlobalValue";
import UserData from "../../data/UserData";
import MathUtil from "../../utils/MathUtil";
import ObjectUtil from "../../utils/ObjectUtil";
const { ccclass, property } = cc._decorator;

@ccclass
export default class WxApi extends Singleton {
    public init() {
        if (wx.onHide) {
            wx.onHide(() => {
                if (GlobalValue.is_sharing)
                    GlobalValue.onHideDate = new Date()
                //暂停游戏
            })
        }

        if (wx.onShow) {
            wx.onShow(() => {
                //如果正在分享
                if (GlobalValue.is_sharing) {
                    GlobalValue.onShowDate = new Date()
                    GlobalValue.is_sharing = false;
                    //分享成功，执行奖励
                    if (this.isShareSuccess()) {
                        this._shareCallFunc && this._shareCallFunc.onSuccess && this._shareCallFunc.onSuccess();
                        this._shareCallFunc = null;
                    }
                    //分享失败，弹窗提示
                    else {
                        let temp = {
                            title: "分享失败",
                            content: "请重新分享",
                            sureCb: () => { this.shareAppMessage(null) },
                            cancelCb: null,
                            cancelText: `取消`,
                            confirmText: `确定`
                        }
                        this.showModal(temp)
                    }
                }

            })
        }
    }
    //-----------------------提示--------------------------------------
    /**
     * 显示消息提示框
     * @param param  title 提示的内容
     * @param param icon 图标
     */
    public showToast(param: { title?: string, icon?: "success" | "loading" | "none", image?: string, duration?: number, success?: () => void, fail?: () => void, complete?: () => void }) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.showToast) return;
        wx.showToast(param)
    }

    /**
     * 显示模态对话框
     * @param param  title 提示标题
     * @param param  content 提示内容
     * @param param  sureCb 确认按钮回调
     * @param param  cancelCb 提示标题
     * @param param  cancelText 取消按钮的文字，最多 4 个字符
     * @param param  confirmText 确认按钮的文字，最多 4 个字符
     */
    public showModal(param: { title?: string, content?: string, sureCb?: Function, cancelCb?: Function, cancelText?: string, confirmText?: string }) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.showModal) return
        try {
            wx.showModal({
                title: param.title,
                content: param.content,
                showCancel: true,//是否显示取消按钮
                cancelText: param.cancelText,
                confirmText: param.confirmText,
                success(res) {
                    if (res.confirm) {
                        param.sureCb && param.sureCb()
                    } else if (res.cancel) {
                        param.cancelCb && param.cancelCb()
                    }
                },
            });
        } catch (e) {
            console.error('showModal异常', e);
        }


    }

    //-----------------------分享--------------------------------------
    private _shareCallFunc: any = null;
    private _share_intervals: number[] = [0, 1, 3]
    /**根据分享时间判断是否分享成功 */
    private isShareSuccess() {
        let interval = GlobalValue.onShowDate.getSeconds() - GlobalValue.onHideDate.getSeconds()
        let probability = 0
        if (interval >= this._share_intervals[0] && interval <= this._share_intervals[1]) {
            probability = 0
        } else if (interval > this._share_intervals[1] && interval <= this._share_intervals[2]) {
            probability = 50
        } else {
            probability = 100
        }
        let random = MathUtil.randomRangeInt(0, 100)
        if (probability >= random) {
            //分享成功
            return true;
        } else {
            //分享失败
            return false
        }
    }
    /**
     * 主动拉起转发，进入选择通讯录界面
     * @param param onSuccess 成功回调
     * @param param onFail 失败回调
     * @param param onError 报错回调
     */

    public shareAppMessage(param: { onSuccess?: Function, onFail?: Function, onError?: Function }) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.shareAppMessage) {
            param && param.onSuccess && param.onSuccess();
            return;
        }
        try {
            GlobalValue.is_sharing = true;
            let msg = {
                title: GameSetting.getInstance().share_info[0].title,
                imageUrl: GameSetting.getInstance().share_info[0].images,
                query: ``,
                imageUrlId: '',
                templateId: '',
                desc: ''
            };
            wx.shareAppMessage(msg);
            this._shareCallFunc = null;
            this._shareCallFunc = ObjectUtil.deepCopy(param)//深拷贝一份避免引用修改
        } catch (e) {
            console.error('shareAppMessage异常', e);
        }
    }
    //-----------------------按钮授权--------------------------------------
    private _btnAuthorize = null
    /**
     * 创建授权按钮
     * @param parentNode 授权按钮父节点
     * @param onSuccess 成功回调
     * @param onFail 失败回调
     * @param position cocos世界坐标
     * @param width 按钮宽度
     * @param height 按钮高度
     */
    public createUserInfoButton(
        parentNode: cc.Node, onSuccess: Function, onFail: Function, position: cc.Vec2, width: number, height: number) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME) {
            onSuccess && onSuccess()
            return;
        }
        let self = this;//记录一下this地址,避免丢失

        let systemInfo = null;
        wx.getSystemInfo({
            success: function (res) {
                let ratio = res.windowWidth / cc.winSize.width;
                width = ratio * width;
                height = ratio * height;
                position.x = ratio * position.x;
                position.y = ratio * position.y;
                createButton();
            }
        });
        let createButton = () => {
            if (self._btnAuthorize) {
                this.destroyAuthBtn();
            }
            self._btnAuthorize = wx.createUserInfoButton({
                type: 'text',
                text: '',
                style: {
                    left: position.x - width / 2,
                    top: systemInfo.windowHeight - position.y - height / 2,
                    width: width,
                    height: height,
                    backgroundColor: "",
                    borderColor: "",
                    borderWidth: 0,
                    borderRadius: 4,
                    textAlign: "center",
                    fontSize: 14,
                    lineHeight: 40,
                }
            });
        }
        self._btnAuthorize.onTap((res) => {
            console.log("授权 ontap", res)
            if (res.errMsg === "getUserInfo:ok") {
                UserData.getInstance().setProperty({
                    headimgurl: res.userInfo.avatarUrl,
                    nickname: res.userInfo.nickName,
                    sex: res.userInfo.gender,
                    language: res.userInfo.language,
                    province: res.userInfo.province,
                    city: res.userInfo.city,
                    country: res.userInfo.country
                })
                self.destroyAuthBtn();
                onSuccess && onSuccess()
            }
            else {
                onFail && onFail()
            }
        });
        self._btnAuthorize.parent = parentNode;
    }
    /**销毁授权按钮 */
    public destroyAuthBtn() {
        if (this._btnAuthorize) {
            this._btnAuthorize.hide()
            this._btnAuthorize.destroy()
            this._btnAuthorize = null;
        }
    }
    //-----------------------常亮--------------------------------------
    /**常亮
    * @param keepScreenOn 是否显示常亮,缺省为true.
    */
    public setKeepScreenOn(keepScreenOn: boolean = true) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.setKeepScreenOn) return;
        wx.setKeepScreenOn({
            keepScreenOn
        })
    }

    //----------------------------震动-------------------------------------
    /**短震动 */
    public vibrateShort() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.vibrateShort) return;
        let param = {
            success: () => { },
            fail: () => { },
            complete: () => { }
        }
        wx.vibrateShort(param)
    }

    /**长震动 */
    public vibrateLong() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.vibrateLong) return;
        let param = {
            success: () => { },
            fail: () => { },
            complete: () => { }
        }
        wx.vibrateLong(param)
    }
    //----------------------------跳转-------------------------------------
    /**
     * 打开另一个小程序
     * @param info 盒子信息:  appId目标小程序 ---path目标页面路径(如果为空则打开首页)
     * @param type  源盒子的类型
     * @param onSuccess 接口调用成功的回调函数
     * @param onFail    接口调用失败的回调函数
     * @param onComplete 接口调用结束的回调函数（调用成功、失败都会执行）
     */
    public navigateToMiniProgram(info: any, type?: string, onSuccess?: Function, onFail?: Function, onComplete?: Function) {
        console.log("跳转数据", info, type)
        return new Promise<void>((resolve, reject) => {
            if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.navigateToMiniProgram) {
                reject(null)
                return
            }
            wx.navigateToMiniProgram({
                appId: info.appid,
                path: info.path,
                success: () => {
                    let param = {
                        id: info.id,
                        images: info.images,
                        images_id: info.images_id,
                        name: info.name
                    }
                    //上传跳转数据
                    onSuccess && onSuccess();
                    resolve(null)
                },
                fail: () => {
                    onFail && onFail();
                    reject(null)
                },
                complete: () => {
                    onComplete && onComplete();
                }
            })
        })

    }
    //----------------------------激励视频------------------------------------
    private _videoAd: RewardedVideoAd = null;
    private _videoIdx: number = 0;
    private _videoCb = null;
    /**展示激励视频 */
    public showVideoAd(param: { onSuccess?: Function, onFail?: Function, onError?: Function }) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.createRewardedVideoAd) {
            param && param.onSuccess && param.onSuccess()
            return;
        }
        //暂停游戏
        this._videoCb = param //不销毁视频对象的时候,需要重新赋值回调
        let adUnitId: string = GameSetting.getInstance().ad_videoID[this._videoIdx];
        if (this._videoIdx >= GameSetting.getInstance().ad_videoID.length) {
            this._videoIdx = 0;
        }
        if (adUnitId == "" || adUnitId == undefined) {
            console.log(`激励视频 - 没有id`)
            return;
        }
        //1 没有激励视频广告组件 - 创建
        if (!this._videoAd) {
            this._videoAd = wx.createRewardedVideoAd({ adUnitId: adUnitId })
            this._videoAd.load().then(() => {
                this._videoAd.show()
            })
            this._videoAd.onLoad(() => { })
            this._videoAd.onError(err => {
                // 激励视频异常，改成分享.
            })
            this._videoAd.onClose(res => {
                if (res && res.isEnded || res === undefined) {
                    this._videoCb && this._videoCb.onSuccess && this._videoCb.onSuccess()
                } else {
                    this._videoCb && this._videoCb.onSuccess && this._videoCb.onFail();
                }
                //恢复游戏
            })
            //2 有激励视频广告组件 - 展示
        } else {
            this._videoAd.show()
                .then(() => {
                })
                .catch(err => {
                    this._videoAd.load()
                        .then(() => { });
                });
        }

    }

    //----------------------------原生广告-------------------------------------
    private _def_Position: cc.Vec2 = cc.v2(75, cc.winSize.height / 2 - 30);
    private _customAd = null;//原生模板广告组件
    private _customIndex: number = 0;//原生id下标
    /**
     * 创建原生广告 
     * @param position 原生广告节点的世界坐标，建议锚点为（0,1）左上角。
     */
    public createCustomAd(position: cc.Vec2):void{
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !wx.createRewardedVideoAd || GameSetting.getInstance().ad_CustomID.length === 0)
            return;
        if (!position) position = this._def_Position
        if (this._customAd) this._customAd = null;
        if (this._customIndex >= GameSetting.getInstance().ad_CustomID.length) {
            this._customIndex = 0;
        }
        let adUnitId: string = GameSetting.getInstance().ad_CustomID[this._customIndex++];
        this.convertToWxSpace(position).then((res) => {
            let pos = res;
            let param: any = {
                adUnitId: adUnitId,
                style: {
                    left: pos.x,
                    top: pos.y,
                    fixed: true
                }
            }
            this._customAd = wx.createCustomAd(param)
            this._customAd.onload(() => {
                this._customAd.show()
            })
            this._customAd.onError((e) => {
                console.error('initCustomAd异常', e);
            })
        })

    }

    /**销毁原生广告 */
    public destroyCustomAd() {
        if (this._customAd) {
            this._customAd = null;
            this._customAd.destroy()
        }
    }

    //----------------------------坐标-------------------------------------
    /**cocos世界坐标转微信平台坐标系 */
    public convertToWxSpace(pos: cc.Vec2) {
        if (!pos) return;
        let temp: cc.Vec2 = cc.v2();
        return new Promise<cc.Vec2>((resolve, reject) => {
            try {
                wx.getSystemInfo({
                    success: function (res) {
                        let ratio = res.windowWidth / cc.winSize.width;
                        temp.x = ratio * pos.x;
                        temp.y = ratio * pos.y;
                        temp.y = res.windowHeight - temp.y
                        resolve(temp)
                    }
                });
            } catch (e) {
                reject()
            }

        })
    }


}
